import { TEMP_DIR } from "./../media/config";
import { COL_MEDIA, COL_MEDIA_CACHE } from "./config";
import { Tags } from "node-id3";
import { initDB } from "./index";
import { IMP3Query } from "../media/query";
import { info, debug } from "../utils/log";
import { provideMediaFiles } from "../media";
import { ensureConfigFiles, genVirtualPath, safeRemoveDir } from "../utils/fs";

export interface IDataMP3 extends Tags {
	virtualPath: string;
	label: string;
	key: string;
	tags: string[];
	mediatype: "AUDIO" | "VIDEO";
}

/**
 * 读取所有MP3数据
 */
export async function getMP3(query: IMP3Query = {}) {
	const tags: IDataMP3[] = [];
	const db = await initDB();
	const media = db.collection(COL_MEDIA);

	const cursor = media.find(query);
	const array = await cursor.toArray();

	array.forEach((item) => {
		if (query.mediatype) {
			if ((item as unknown as IDataMP3).mediatype === query.mediatype) {
				tags.push(item as unknown as IDataMP3);
			}
		} else {
			tags.push(item as unknown as IDataMP3);
		}
	});

	return tags;
}

/**
 * 更新所有MP3数据
 */
export async function updateMP3() {
	info("MP3 collection updating");

	const db = await initDB();
	const mp3 = db.collection(COL_MEDIA);
	const data = await provideMediaFiles();

	data.forEach(async (item) => {
		const key = (await item).key;
		const keyExist = await existKey(key);
		if (!keyExist) {
			await mp3.insertOne(item);
		}
	});

	info("MP3 collection is updated");
}

/**
 * 初始化MP3数据
 */
export async function initMP3() {
	ensureConfigFiles();
	safeRemoveDir(TEMP_DIR, true);
	await updateMP3();
	info("MP3 collection is initialized");
}

/**
 * 判断 key 是否存在
 */
export async function existKey(key: string) {
	const db = await initDB();
	const media = db.collection(COL_MEDIA);
	const arr = await media.find({ key }).toArray();
	return arr.length;
}

/**
 * 判断 Label 是否 Cache 中存在
 */
export async function existCacheLabel(label: string) {
	const db = await initDB();
	const cacheDB = db.collection(COL_MEDIA_CACHE);
	const arr = await cacheDB.find({ label }).toArray();
	return arr.length;
}

/**
 * 判断 filename 是否存在
 */
export async function existFilename(filename: string) {
	const db = await initDB();
	const media = db.collection(COL_MEDIA);
	const virtualPath = genVirtualPath(filename);
	const arr = await media.find({ virtualPath }).toArray();
	return arr.length;
}
